<template>
    <n-popover trigger="hover">
        <template #trigger>
            <n-button
                class="main-framework-header-func_button"
                @click="showPopover = !showPopover"
                quaternary
                circle>
                <template #icon>
                    <n-icon size="20px"><FormatListBulletedRound /></n-icon>
                </template>
            </n-button>
        </template>
        <span>任务中心</span>
    </n-popover>
    <!-- -------------------------------------------------- -->
    <div id="com_modal_taskCenter" class="quick-item-modal-card quick-item-modal-nomodal">
        <n-modal
            to="#com_modal_taskCenter"
            v-model:show="showPopover"
            title="任务中心"
            size="small"
            preset="card"
            draggable
            :trap-focus="false"
            :style="{ width: '80%' }">
            <div>
                <n-table size="small">
                    <thead>
                        <tr>
                            <th class="col-index"></th>
                            <th class="col-id">ID</th>
                            <th class="col-cmd">命令</th>
                            <th class="col-start">开始时间</th>
                            <th class="col-duration">运行时间</th>
                            <th class="col-end">结束时间</th>
                            <th class="col-status">
                                <div style="display: flex">
                                    状态
                                    <n-dropdown
                                        trigger="hover"
                                        :options="tableControl.filter.status.options"
                                        @select="
                                            (p1: string) => {
                                                tableControl.filter.status.value = p1
                                                tableControl.filter.status.options.forEach((item) => {
                                                    if (item.key == p1) item.label = item.label + '√'
                                                    else item.label = item.label.replace('√', '')
                                                })
                                            }
                                        "
                                        :render-label="tableControl.filter.status.render_label">
                                        <n-button quaternary circle size="tiny">
                                            <template #icon>
                                                <n-icon v-if="tableControl.filter.status.value == 'N'">
                                                    <FilterListOffFilled />
                                                </n-icon>
                                                <n-icon v-else>
                                                    <FilterListRound />
                                                </n-icon>
                                            </template>
                                        </n-button>
                                    </n-dropdown>
                                </div>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr
                            v-for="(item, index) in tableControl.filter.global_filted_data"
                            :key="item.task_id">
                            <td class="col-index">{{ index + 1 }}</td>
                            <td class="col-id">{{ item.task_id }}</td>
                            <td class="col-cmd">{{ item.cmd }}</td>
                            <td class="col-start">{{ formatToCompactDateTime(item.start_time) }}</td>
                            <td class="col-duration">{{ duration(item) }}</td>
                            <td class="col-end">{{ formatToCompactDateTime(item.end_time) }}</td>
                            <td class="col-status">{{ item.status }}</td>
                        </tr>
                    </tbody>
                </n-table>
                <p v-if="tableControl.data.length == 0" style="text-align: center; margin: 3rem">
                    无任务
                </p>
            </div>
        </n-modal>
    </div>
</template>

<script setup lang="ts">
import { computed, h, reactive, ref, watch } from 'vue'
import { FormatListBulletedRound } from '@vicons/material'
import { axg_getTaskList, type TaskItem } from '@/utils/interface/TaskItem'
import { FilterListOffFilled, FilterListRound } from '@vicons/material'
import type { DropdownOption } from 'naive-ui'

const showPopover = ref(false)

const now = ref(Date.now())
let interval1: any = null
let interval5: any = null
const tableControl = reactive({
    data: [] as Array<TaskItem>,
    data_backup: [] as Array<TaskItem>,
    async handleGetTaskList() {
        tableControl.data = await axg_getTaskList()
        tableControl.data_backup = [...tableControl.data]
    },

    filter: {
        global_filted_data: computed<Array<TaskItem>>(() => {
            let dataSource: Array<TaskItem> = tableControl.data

            if (tableControl.filter.status.value != 'N') {
                dataSource = dataSource.filter((item) => item.status == tableControl.filter.status.value)
            }
            return dataSource
        }),
        status: {
            value: 'N',
            options: [
                {
                    label: '无筛选',
                    key: 'N',
                    active: false
                },
                {
                    label: '已完成',
                    key: '已完成',
                    active: false
                },
                {
                    label: '正在运行',
                    key: '正在运行',
                    active: false
                },
                {
                    label: '未开始',
                    key: '未开始',
                    active: false
                },
                {
                    label: '错误',
                    key: '错误',
                    active: false
                }
            ],
            render_label: (option: DropdownOption) => {
                return h('span', {}, option.label as string)
            }
        }
    }
})

const formatDuration = (ms: number) => {
    const seconds = Math.floor(ms / 1000) % 60
    const minutes = Math.floor(ms / 1000 / 60) % 60
    const hours = Math.floor(ms / 1000 / 60 / 60)
    return `${hours ? hours + 'h' : ''}${minutes ? minutes + 'm' : ''}${seconds}s`
}
function formatToCompactDateTime(dateStr: string) {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    const year = date.getFullYear().toString().slice(-2)
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return `${year}${month}${day}T${hours}:${minutes}:${seconds}`
}
const duration = (item: TaskItem) => {
    if (!item.end_time) {
        const t = now.value - new Date(item.start_time).getTime()
        return t < 0 ? '0s' : formatDuration(t)
    } else {
        return formatDuration(new Date(item.end_time).getTime() - new Date(item.start_time).getTime())
    }
}

/////////////////////////////////////////////

watch(
    () => showPopover.value,
    (nv, _ov) => {
        if (nv) {
            tableControl.handleGetTaskList()
            interval1 = setInterval(() => {
                now.value = Date.now()
            }, 1000)
            interval5 = setInterval(() => {
                tableControl.handleGetTaskList()
            }, 5000)
        } else {
            window.clearInterval(interval1)
            window.clearInterval(interval5)
        }
    }
)

defineExpose({})
</script>

<style lang="scss" scoped>
.main-framework-header-func_button:hover {
    background-color: #f0f0f070;
    color: orange;
}

.col-index {
    width: 0;
}
</style>
